#include "stdafx.h"

#include "StickyTweetsXP.h"

#include "StatusEdit.h"

LRESULT CALLBACK StatusEdit(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, UINT_PTR pSubClassId, DWORD_PTR pReferenceData)
{
  switch (message)
  {
  case WM_PASTE:
    StatusEdit_Paste();
    return 0;

  case WM_CHAR:
    switch (wParam)
    {
    case VK_RETURN:
      UpdateStatus(hWnd);
      return 0;

    case VK_TAB:
    case VK_ESCAPE:
      SendMessage(hWndStickyTweets, message, wParam, lParam);
      return 0;
    }
    break;

  case WM_KEYUP:
    UpdateStatusControls(!(wParam == VK_RETURN || wParam == VK_TAB || wParam == VK_ESCAPE));
    break;

  case WM_KEYDOWN:
    switch (wParam)
    {
    case VK_HOME:
    case VK_END:
      if (GetWindowTextLength(hWnd) > 0)
        return DefSubclassProc(hWnd, message, wParam, lParam);
      else
        SendMessage(hWndStickyTweets, message, wParam, lParam);
      break;

    case VK_UP:
    case VK_DOWN:
    case VK_PRIOR:
    case VK_NEXT:
    case VK_F5:
      SendMessage(hWndStickyTweets, message, wParam, lParam);
      return 0;
    }
    break;
  }
  return DefSubclassProc(hWnd, message, wParam, lParam);
}

VOID StatusEdit_Paste(VOID)
{
  HGLOBAL globalData;
  LPTSTR  pasteText;

  if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
    return;

  if (!OpenClipboard(hWndStickyTweets)) 
    return;

  globalData = GetClipboardData(CF_UNICODETEXT);

  if (globalData != NULL)
    pasteText = (LPTSTR)(GlobalLock(globalData));

  StickyTweetsAppXP& app = StickyTweetsAppXP::GetInstance();

  CString startString(pasteText);
  CString rs, pasteString, trimmedUrl;

  startString.Replace('\n', ' ');
  rs.LoadStringW(IDS_REGEX_URL);
  wregex linkFinder(rs);
  wcmatch mr;

  INT pos = 0;
  while (regex_search(startString.Mid(pos).GetString(), mr, linkFinder))
  {
    pasteString.Append(startString.Mid(pos, mr.position(0)));
    if (app.TrimUrl(startString.Mid(pos + mr.position(0), mr.length(0)), trimmedUrl) == StatusStOk)
      pasteString.Append(trimmedUrl);
    else
      pasteString.Append(startString.Mid(pos, mr.position(0)));

    pos += mr.position(0) + mr.length(0);
  }
  
  pasteString.Append(startString.Mid(pos));

  Edit_ReplaceSel(hWndStatus, pasteString);

  if (pasteText != NULL)
    GlobalUnlock(globalData);

  CloseClipboard();
}